from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseBadRequest
from django.template.loader import render_to_string

from ..models import Article
from .models import ArticleComment

from tranos.decorators import ajax_required


@login_required
@ajax_required
def create(request, article_id):
    try:
        if request.method == 'POST':
            article = get_object_or_404(Article, pk=article_id)
            comment = request.POST.get('comment')
            comment = comment.strip()
            if len(comment) > 0:
                parent_id = request.POST.get('parent')
                parent = None
                if parent_id != None:
                    parent = get_object_or_404(ArticleComment, pk=parent_id)
                article_comment = ArticleComment(user=request.user, article=article, comment=comment, parent=parent)
                article_comment.save()
                html = render_to_string('translations/comments/partial_article_comment.html', {'comment': article_comment})
                return HttpResponse(html)
            else:
                raise
        else:
            return HttpResponseBadRequest()
    except Exception:
        return HttpResponseBadRequest()


@login_required
@ajax_required
def delete(request):
    try:
        if request.method == 'POST':
            comment_id = request.POST.get('comment')
            comment = get_object_or_404(ArticleComment, pk=comment_id)
            if comment.user == request.user:
                comment.delete()
                return HttpResponse(comment_id)
            else:
                raise
    except Exception:
        return HttpResponseBadRequest()
